<?php
require_once('config/config.inc');
	// Provides functions for user account API calls
	class User{
		function __construct($rwConn){
			// Check session for current login
			// If exists validate hash then fill out members
			$this->rwConn = $rwConn;
			if($this->rwConn->errno){
				$this->_killMe("Database Error");
			}
			if(isset($_COOKIE['_u']) && isset($_COOKIE['_h']) && isset($_COOKIE['_s'])){
				$userId = $_COOKIE['_u'];
				$userHash = $_COOKIE['_h'];
				$userSesh = $_COOKIE['_s'];
				$myHash = $this->_genHash($userId);
				if($myHash === $userHash){
					// Compare user session to database
					$sql = "SELECT session,first_name,last_name,email,privilege FROM User WHERE user_id = '{$userId}' LIMIT 1";
					$result = $this->rwConn->query($sql);
					if($result->num_rows){
						$result = $result->fetch_assoc();
						$mySesh = $result['session'];
						if(!is_null($mySesh) && $mySesh == $userSesh){
							$this->userId = $userId;
							$this->email = $result['email'];
							$this->firstName = $result['first_name'];
							$this->lastName = $result['last_name'];
							$this->loggedIn = true;
							$this->admin = $result['privilege']==0?true:false;
							return ;
						}
					}
				}
			}
			$this->email = null;
			$this->firstName = null;
			$this->lastName = null;
			$this->loggedIn = false;
			$this->admin = false;
		}
		 
		public function register(){
			global $paramArray;
			$email = isset($paramArray['email'])?$paramArray['email']:null;
			$password = isset($paramArray['password'])?$paramArray['password']:null;
			$firstName = isset($paramArray['firstName'])?$paramArray['firstName']:null;
			$lastName = isset($paramArray['lastName'])?$paramArray['lastName']:null;

			if(is_null($email)) return array("success"=>false,"message"=>"Email could not be empty");
			if(is_null($password)) return array("success"=>false,"message"=>"Password could not be empty");
			if(is_null($firstName)) return array("success"=>false,"message"=>"First Name could not be empty");
			if(is_null($lastName)) return array("success"=>false,"message"=>"Last Name could not be empty");

			if(strlen($password)!==32) return array("success"=>false,"message"=>"Password must be MD5 encrypted");
			$sql = "SELECT count(*) FROM User WHERE email = '{$email}'";
			$count = $this->rwConn->query($sql);
			list($count) = $count->fetch_array();

			if($count) return array("success"=>false,"message"=>"Email already taken");

			$sql = "INSERT INTO User (email,password,first_name,last_name) VALUES ('{$email}','{$password}','{$firstName}','{$lastName}')";
			$this->rwConn->query($sql);
			checkDbError();
			$userId = $this->rwConn->insert_id;
			


			$retVal = array("success"=>true,"userId"=>$userId,"message"=>"Successfully Registered");
		return $retVal;	
			
		}
		public function getEmailFromUid()
		{
			global $paramArray;
			if(empty($paramArray['userId']))
			{
				$retVal = array("success"=>false, "message"=>"userID not set!");
				return $retVal;
			}
			$sql = "Select email from User where user_id='{$paramArray['userId']}'";
			$result= $this->rwConn->query($sql);
			if($result->num_rows !=1){
				$retVal['message'] = "UserID not found!";
				$retVal['success'] = "false";
				return $retVal;
			}
			$uId = $result->fetch_assoc();
			$retVal['success'] = true;
			$retVal['email'] = $uId['email'];
			return $retVal;
		}
		public function getUidFromEmail()
		{
			global $paramArray;
			if(empty($paramArray['email']))
			{
				$retVal = array("success"=>false, "message"=>"Email not set!");
				return $retVal;
			}
			$sql = "Select user_id from User where email='{$paramArray['email']}'";
			$result= $this->rwConn->query($sql);
			if($result->num_rows !=1){
				$retVal['message'] = "Email not found!";
				$retVal['success'] = "false";
				return $retVal;
			}
			$uId = $result->fetch_assoc();
			$retVal['success'] = true;
			$retVal['userId'] = $uId['user_id'];
			return $retVal;
		}
		public function login(){
			global $paramArray;
			
			$retVal = array("success"=>false,"userId"=>-1,"message"=>"General Failure");

			$email = (isset($paramArray['email']))?$paramArray['email']:false;
			$password = (isset($paramArray['password']))?$paramArray['password']:false;
			$expire = (isset($paramArray['remember']) && $paramArray['remember'] === 1)?time()+31556926:0; // 1 year or on close browser
			
			if($email === false){
				$retVal['message'] = "Email is empty";
				return $retVal;
			}		
			if($password === false){
				$retVal['message'] = "Password is empty";
				return $retVal;
			}
			$sql = "SELECT user_id,first_name,last_name,email,privilege FROM User WHERE email = '$email' AND password = '$password' LIMIT 1";
			$result = $this->rwConn->query($sql);
			if($result->num_rows){
				$result = $result->fetch_assoc();
				$session = md5(time());
				$hash = $this->_genHash($result['user_id']);
				$this->userId = $result['user_id'];
				$this->email = $result['email'];
				$this->firstName = $result['first_name'];
				$this->lastName = $result['last_name'];
				$this->loggedIn = true;
				$this->admin = $result['privilege']==0?true:false;
				setcookie('_u',$this->userId,$expire,'/');
				setcookie('_h',$hash,$expire,'/');
				setcookie('_s',$session,$expire,'/');
				$sql = "UPDATE User SET session = '{$session}' WHERE user_id = {$this->userId} LIMIT 1";
				$this->rwConn->query($sql);
				$retVal['userId'] = $this->userId;
				$retVal['success'] = true;
				$retVal['message'] = "Login Successful";
				return($retVal);
			}
			$retVal['message'] = "Login Not Found";
			return $retVal;
			
		}
		public function logout(){
			setcookie('_u',0,-1,'/');
			setcookie('_h',0,-1,'/');
			setcookie('_s',0,-1,'/');
			return array("success"=>true,"message"=>"Logout Success");
	
		}
		public function isAdmin(){			
			return array("success"=>$this->admin,"message"=>"");	
		}
		public function getInfo(){

			
			if( $this->loggedIn == true)
			{
				$information['success'] = true;
				$information['userId']= $this->userId;
				$information['email'] = $this->email;
				$information['firstName'] = $this->firstName;
				$information['lastName'] = $this->lastName;
				$information['admin'] = $this->admin;
				

				return $information;
			}
	
			return array("success"=>false,"message"=>"User not logged in!");

		}
		public function editInfo(){
			global $paramArray;
			$update['email'] = isset($paramArray['email'])?$paramArray['email']:'';
			$update['password'] = isset($paramArray['password'])?$paramArray['password']:'';
			$update['first_name'] = isset($paramArray['firstName'])?$paramArray['firstName']:'';
			$update['last_name'] = isset($paramArray['lastName'])?$paramArray['lastName']:'';
			$updateList = array();
			foreach($update as $key=>$value){
				if(!empty($value)){
					$updateList[] = "$key = '$value'";
				}
			}
			

			if(empty($updateList))
				return array("success"=>false,"message"=>"Nothing to update");
				
			$sql = "UPDATE User SET ".implode(',',$updateList)." WHERE user_id = {$this->userId} LIMIT 1";
			$this->rwConn->query($sql);

			if($this->rwConn->affected_rows){
				return array("success"=>true,"message"=>"Info Updated");

			}
			
			return array("success"=>false,"message"=>"Nothing to update");

		}
		public function getMyProject(){
			$retVal = array("success"=>false,"message"=>"General Failure");
			$sql = "SELECT proj_id FROM UID_Project_Association WHERE user_id = {$this->userId}";
			$result = $this->rwConn->query($sql);
			if(!($result->num_rows)){
				$retVal['message'] = "User is not assigned to a project";
				return $retVal;
			}
			while($row = $result->fetch_assoc()){
				$retVal['projectIds'][] = $row['proj_id'];
			}
			$retVal['message'] = "OK";
			return $retVal;
		}
		public function isLoggedIn(){
			return array("success"=>$this->loggedIn,"message"=>"");
		}
		public function listUsers(){
			if( $this->admin == true){
				$sql = "SELECT user_id,email,privilege FROM User";
				$result = $this->rwConn->query($sql);
				checkDbError();
				$toReturn = array();
				while($row = $result->fetch_assoc()){
	                    $toReturn[] = $row;
	            }
	            $retVal['success'] = true;
				$retVal['users'] = $toReturn;
				return $retVal;
			}
			
			return array("success"=>false,"message"=>"Insufficient Privelege");

				
		}
		public function promoteUser(){

		global $paramArray;
		if( $this->admin == true){
		$sql = "SELECT * FROM User WHERE user_id = '{$paramArray['userId']}'";
		$result = $this->rwConn->query($sql);
		if(!($result->num_rows)){
				$retVal['message'] = "User is not in the table";
				return $retVal;
		}
		
	
		$sql = "UPDATE User SET privilege = 0 WHERE user_id = '{$paramArray['userId']}'";	
		$this->rwConn->query($sql);
			
		return array("success"=>true,"message"=>"User promoted!");
				
		}
		
		return array("success"=>false,"message"=>"Insufficient Privelege");

		}	
		
		public function demoteUser(){

		global $paramArray;
		if( $this->admin == true){
		$sql = "SELECT * FROM User WHERE user_id = '{$paramArray['userId']}'";
		$result = $this->rwConn->query($sql);
		if(!($result->num_rows)){
				$retVal['message'] = "User is not in the table";
				return $retVal;
		}
		
	
		$sql = "UPDATE User SET privilege = 1 WHERE user_id = '{$paramArray['userId']}'";	
		$this->rwConn->query($sql);
			
		return array("success"=>true,"message"=>"User Demoted!");
				
		}
		
		return array("success"=>false,"message"=>"Insufficient Privelege");

		}	
		
		private function _killMe($message="Unknown Error"){
			die(json_encode(array("success"=>false,"message"=>$message)));
		}
		private function _genHash($userId){
			$salt1 = 'CUc0qUGMmmL9SAT';
			$salt2 = 'fgZrAQGFfuVCUmV';
			return md5($userId.$salt1).md5($salt2.$userId);
		}
		private $rwConn;
		private $userId;
		private $email;
		private $firstName;
		private $lastName;
		private $loggedIn;
		private $admin;
	};


